<template>
  <div
    class="page-wrap"
    v-loading="loading"
    element-loading-text="正在加载中..."
  >
    <!-- 顶部导航条 -->
    <header class="page-header">
      <div class="brand">
        <div class="logo">🛍️</div>
        <h1 class="brand-name">商品搜索中心</h1>
      </div>

      <!-- 搜索区 -->
      <section class="search-section">
        <SearchBar v-model:keyword="keyword" @search="fetchData" />
      </section>

      <!-- 头部操作区 -->
      <HeaderActions
        :current-platform="currentPlatform"
        :exporting="exporting"
        :data-basket="dataBasket"
        @open-platform-selector="platformSelectorRef.show()"
        @export="handleExport"
        @open-data-basket="dataBasketDialogRef.show()"
      />
    </header>

    <!-- 内容区 -->
    <section class="result-section">
      <!-- 欢迎页 -->
      <ResultWelcome
        v-if="total === null"
        @focus="focusSearch"
        @demo="search"
      />

      <!-- 无结果页 -->
      <ResultEmpty v-else-if="total === 0" @reset="resetSearch" />

      <!-- 有数据 -->
      <ProductTable
        v-else
        :table-data="tableData"
        :total="total"
        :page="page"
        :is-in-basket="isInBasket"
        @toggle-basket="toggleInBasket"
        @all-toggle-basker="alljoin"
        @form-change="formChange"
      />
    </section>

    <!-- 平台选择弹窗 -->
    <PlatformSelector
      :platforms="platforms"
      ref="platformSelectorRef"
      @select="onPlatformSelect"
    />

    <!-- 数据篮弹窗 -->
    <DataBasketDialog
      ref="dataBasketDialogRef"
      :data-basket="dataBasket"
      @remove="toggleInBasket"
      @clear="clearBasket"
      @export="exportBasket"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import apiClient from "@/utils/api";
import PlatformSelector from "@/components/PlatformSelector.vue";
import * as XLSX from "xlsx";

// 导入拆分后的组件
import SearchBar from "@/components/SearchBar.vue";
import HeaderActions from "@/components/HeaderActions.vue";
import ResultWelcome from "@/components/ResultWelcome.vue";
import ResultEmpty from "@/components/ResultEmpty.vue";
import ProductTable from "@/components/ProductTable.vue";
import DataBasketDialog from "@/components/DataBasketDialog.vue";

const platforms = [
  { name: "淘宝", code: "taobao" },
  { name: "天猫", code: "tmall" },
  { name: "京东", code: "jd" },
  { name: "拼多多", code: "pinduoduo" },
  { name: "抖音", code: "douyin" },
];
const platformSelectorRef = ref();
const dataBasketDialogRef = ref();
const currentPlatform = ref(platforms[0]);
const keyword = ref("");
const tableData = ref([]);
const total = ref(null);
const page = ref(1);
const loading = ref(false);
const exporting = ref(false);
const showBasketDialog = ref(false);
const dataBasket = ref([]);

// 数据篮逻辑（保持在主组件，因为是共享状态）
const initBasket = () => {
  const saved = localStorage.getItem("dataBasket");
  if (saved) {
    try {
      dataBasket.value = JSON.parse(saved);
    } catch (e) {
      dataBasket.value = [];
    }
  }
};

const isInBasket = (numIid) => {
  return dataBasket.value.some((item) => item.num_iid === numIid);
};

const toggleInBasket = (product) => {
  const index = dataBasket.value.findIndex(
    (item) => item.num_iid === product.num_iid
  );
  if (index > -1) {
    dataBasket.value.splice(index, 1);
    ElMessage.info(`已从数据篮移除：${product.title.slice(0, 10)}...`);
  } else {
    const newItem = {
      num_iid: product.num_iid,
      title: product.title,
      pic_url: product.pic_url,
      detail_url: product.detail_url,
      orginal_price: product.orginal_price,
      promotion_price: product.promotion_price,
      sales: product.sales || 0,
      platform: currentPlatform.value.name,
      added_time: new Date().toLocaleString(),
    };
    dataBasket.value.push(newItem);
    ElMessage.success(`已加入数据篮：${product.title.slice(0, 10)}...`);
  }
  localStorage.setItem("dataBasket", JSON.stringify(dataBasket.value));
};

const alljoin = () => {
  let addedCount = 0;
  tableData.value.forEach((product) => {
    const index = dataBasket.value.findIndex(
      (item) => item.num_iid === product.num_iid
    );
    if (index === -1) {
      const newItem = {
        num_iid: product.num_iid,
        title: product.title,
        pic_url: product.pic_url,
        detail_url: product.detail_url,
        orginal_price: product.orginal_price,
        promotion_price: product.promotion_price,
        sales: product.sales || 0,
        platform: currentPlatform.value.name,
        added_time: new Date().toLocaleString(),
      };
      dataBasket.value.push(newItem);
      addedCount++;
    }
  });

  if (addedCount > 0) {
    ElMessage.success(`已全部加入数据篮，共添加 ${addedCount} 条数据`);
    localStorage.setItem("dataBasket", JSON.stringify(dataBasket.value));
  } else {
    ElMessage.info("所有商品均已在数据篮中，无需重复添加");
  }
};

const exportBasket = () => {
  if (dataBasket.value.length === 0) return ElMessage.warning("数据篮为空");
  const ws = XLSX.utils.json_to_sheet(
    dataBasket.value.map((item) => ({
      商品ID: item.num_iid,
      商品标题: item.title,
      图片链接: item.pic_url,
      商品链接: item.detail_url,
      券前价: item.orginal_price,
      券后价: item.promotion_price,
      销量: item.sales,
      所属平台: item.platform,
      添加时间: item.added_time,
    }))
  );
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "我的数据篮");
  XLSX.writeFile(wb, `我的数据篮_${new Date().toLocaleDateString()}.xlsx`);
  ElMessage.success(`已导出 ${dataBasket.value.length} 条数据`);
};

const clearBasket = () => {
  ElMessageBox.confirm("确定要清空数据篮吗？此操作不可恢复。", "清空数据篮", {
    type: "warning",
  }).then(() => {
    dataBasket.value = [];
    localStorage.removeItem("dataBasket");
    ElMessage.success("数据篮已清空");
  });
};

const commonParams = {
  api_key: localStorage.getItem("apiKey"),
  sort: "default",
};

const fetchData = async () => {
  if (!keyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }
  loading.value = true;
  total.value = null;
  try {
    const res = await apiClient.get("/api/v1/product/search", {
      params: {
        platform: currentPlatform.value.code,
        q: keyword.value,
        page: page.value,
        ...commonParams,
      },
    });
    const items = res.data.data?.items?.item || [];
    tableData.value = Array.isArray(items) ? items : [items];
    total.value = res.data.data?.items.page_size || 0;
  } catch (error) {
    ElMessage.error(error.response?.data?.message || "搜索失败");
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const resetSearch = () => {
  keyword.value = "";
  total.value = null;
  tableData.value = [];
};

const focusSearch = async () => {
  await nextTick();
  document.querySelector(".search-card input")?.focus();
};

const search = (keydata) => {
  keyword.value = keydata;
  fetchData();
};

const onPlatformSelect = (platform) => {
  currentPlatform.value = platform;
  localStorage.setItem("lastPlatform", platform.code);
  if (keyword.value) fetchData();
  ElMessage.success(`已切换至 ${platform.name}`);
};

const formChange = (form) => {
  // 把form 赋值给 commonParams
  commonParams.sort = form.sortBySales ? "sales_desc" : "default";
  commonParams.page = form.limit;
  fetchData();
};

const handleExport = async () => {
  if (tableData.value.length === 0) return ElMessage.warning("暂无数据");
  ElMessageBox.confirm(
    '导出选项：\n"全部"：导出所有数据\n"当前页"：导出本页 20 条',
    "导出数据",
    {
      confirmButtonText: "全部",
      cancelButtonText: "当前页",
      distinguishCancelAndClose: true,
    }
  ).then(() => exportCurrent());
};

const exportCurrent = () => {
  const excelData = tableData.value.map((item) => ({
    商品ID: item.num_iid,
    商品标题: item.title,
    图片链接: item.pic_url,
    商品链接: item.detail_url,
    券前价: item.orginal_price,
    券后价: item.promotion_price,
    销量: item.sales,
  }));
  const ws = XLSX.utils.json_to_sheet(excelData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "商品数据");
  XLSX.writeFile(wb, `${currentPlatform.value.name}_当前页.xlsx`);
};

onMounted(() => {
  initBasket();
});
</script>

<style lang="scss">
@use "./SearchView.scss";
</style>
